package com.jdew.thkj.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.SharePictureAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.PddDetailBean;
import com.jdew.thkj.dialog.BottomDialog;
import com.jdew.thkj.dialog.Item;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.ShareManager;
import com.jdew.thkj.manager.WrapContentLinearLayoutManager;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.onitemInterface.OnItemShareClickListener;
import com.jdew.thkj.onitemInterface.OnItemcheckedListener;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.jdew.thkj.utils.ZXingUtils;
import com.jdew.thkj.wxapi.WechatShareManeger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PddSharePictureActivity extends BaseActivity {
    @Bind(R.id.banner)
    ImageView banner;
    @Bind(R.id.share_name)
    TextView shareName;
    @Bind(R.id.share_price)
    TextView sharePrice;
    @Bind(R.id.share_before_price)
    TextView shareBeforePrice;
    @Bind(R.id.share_quan)
    TextView quan;
    @Bind(R.id.share_before_salume)
    TextView salume;
    @Bind(R.id.share_ercode)
    ImageView shareErcode;
    @Bind(R.id.shareView)
    View shareView;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.share)
    TextView share;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.er_view)
    RelativeLayout erView;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.names)
    TextView names;
    @Bind(R.id.s1)
    TextView s1;
    @Bind(R.id.n1)
    TextView n1;
    @Bind(R.id.s2)
    TextView s2;
    @Bind(R.id.n2)
    TextView n2;
    @Bind(R.id.lianjie)
    TextView lianjie;
    @Bind(R.id.copy)
    TextView copy;
    @Bind(R.id.onsale)
    TextView onsale;
    @Bind(R.id.preview)
    RelativeLayout preview;
    @Bind(R.id.shop)
    ImageView shop;
    @Bind(R.id.shopname)
    TextView shopname;
    @Bind(R.id.couple)
    TextView couple;
    @Bind(R.id.duanlian)
    TextView duanlian;
    private WechatShareManeger mShareManager;
    private Bitmap shareBitmap = null;
    private String youhuiquan;
    private List<String> imageList = new ArrayList<>();
    private SharePictureAdapter adapter;
    private int pos;
    private Dialog mShareDialog;
    public SharedPreferences sp;
    public SharedPreferences.Editor editor;
    private String shareUrl;
    private String itemId;
    DecimalFormat df = new DecimalFormat("0.00");


    @Override
    public int bindLayout() {
        return R.layout.activity_share_pic;
    }

    @Override
    public void initView(View view) {
        mShareManager = WechatShareManeger.getInstance(this);
        shareUrl = getIntent().getStringExtra("shareUrl");
        itemId = getIntent().getStringExtra("itemid");
        title.setText("分享预览");
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        GetSingleproduct();
        adapter = new SharePictureAdapter(this, imageList);
        recycleView.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recycleView.setAdapter(adapter);
        adapter.map.put(0,true);
        adapter.setItemCheckedListener(new OnItemcheckedListener() {
            @Override
            public void onitemcheck(int position) {
                Glide.with(PddSharePictureActivity.this).load(imageList.get(adapter.pos)).into(banner);
            }
        });
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        share.setOnClickListener(this);
        copy.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.share: {
                showDialog();
            }
            break;
            case R.id.copy: {
                if (!TextUtils.isEmpty(duanlian.getText())) {
                    RegexValidateUtils.copyText(this, shareName.getText().toString() + "\n" + s1.getText().toString() + "\n" + n1.getText().toString() + "\n" + "【优惠券】  " + youhuiquan  + "\n" + onsale.getText().toString() + "\n" + lianjie.getText().toString()+"\n"+shareUrl);
                    ToastUtils.getInstance(this).showMessage("复制成功");
                }
            }
            break;
            default:
                break;
        }
    }

    /**
     * 显示分享弹出框
     */
    private void showDialog() {
        if (mShareDialog == null) {
            initShareDialog();
        }
        mShareDialog.show();
    }

    /**
     * 初始化分享弹出框
     */
    private void initShareDialog() {
        mShareDialog = new Dialog(this, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(this, R.layout.layout_share, null);
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.VISIBLE);
                if (mShareDialog != null && mShareDialog.isShowing()) {
                    mShareDialog.dismiss();
                }
            }
        });
        view.findViewById(R.id.wx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                        mShareManager.sharePicture(0, shareBitmap);
                    }
                }, 500);
            }
        });
        view.findViewById(R.id.friend_cricle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                        mShareManager.sharePicture(1, shareBitmap);
                    }
                }, 500);
            }
        });
        view.findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                preview.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < imageList.size(); i++) {
                            if (i == pos) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                                        RegexValidateUtils.saveBmp2Gallery(PddSharePictureActivity.this,shareBitmap);
                                    }
                                }).start();
                            } else {
                                final String url = imageList.get(i);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (!url.equals("") && null != url) {
                                            shareBitmap = RegexValidateUtils.returnBitmap(url);
                                            RegexValidateUtils.saveBmp2Gallery(PddSharePictureActivity.this,shareBitmap);
                                        }
                                    }
                                }).start();
                            }
                        }
                    }
                }, 500);
                preview.setVisibility(View.VISIBLE);
                Toast.makeText(PddSharePictureActivity.this, "图片保存成功，请进入相册查看", Toast.LENGTH_SHORT).show();
            }
        });
        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }


    public void GetSingleproduct() {
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetSingleproduct(itemId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "goodsid" + itemId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<PddDetailBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(PddDetailBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    quan.setText(bean.getData().get(0).getCoupon_discount());
                    shareName.setText(bean.getData().get(0).getGoods_name());
                    salume.setText("销量:" + bean.getData().get(0).getSold_quantity());
                    shareBeforePrice.setText(df.format(Double.parseDouble(bean.getData().get(0).getMin_group_price())));
                    shareBeforePrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    sharePrice.setText(df.format(Double.parseDouble(bean.getData().get(0).getCoupon_remain_quantity())));
                    imageList.addAll(bean.getData().get(0).getGoods_gallery_urls());
                    shareErcode.setImageBitmap(ZXingUtils.createQRImage(shareUrl, shareErcode.getWidth(), shareErcode.getHeight()));
                    shop.setImageResource(R.mipmap.pdd_source);
                    shopname.setText(bean.getData().get(0).getMall_name());
                    adapter.setDataList(imageList);
                    lianjie.setText("点击下面的链接,即可领券");
                    s1.setText("【在售价】  " + df.format(Double.parseDouble(bean.getData().get(0).getMin_group_price())) + "元");
                    n1.setText("【抢购价】  " + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_remain_quantity())) + "元");
                    s2.setText("【在售价】  " + df.format(Double.parseDouble(bean.getData().get(0).getMin_group_price())) + "元");
                    n2.setText("【抢购价】  " + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_remain_quantity())) + "元");
                    couple.setText("【优惠券】  " + bean.getData().get(0).getCoupon_discount()+"元");
                    youhuiquan = bean.getData().get(0).getCoupon_discount() + "元";
                    duanlian.setText(shareUrl);
                    Glide.with(PddSharePictureActivity.this).load(imageList.get(0)).into(banner);
                }
            }
        });
    }

    public void share() {
        new BottomDialog(this)
                .title(R.string.share_title)
                .orientation(BottomDialog.HORIZONTAL)
                .inflateMenu(R.menu.menu_share, new OnItemShareClickListener() {
                    @Override
                    public void click(Item item, final int position) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (position == 2) {
                                    shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                                    RegexValidateUtils.saveBmp2Gallery(PddSharePictureActivity.this,shareBitmap);
                                } else {
                                    shareBitmap = RegexValidateUtils.getBitmapByView(shareView);
                                    mShareManager.sharePicture(position, shareBitmap);
                                }
                            }
                        }, 500);
                    }
                }).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        preview.setVisibility(View.VISIBLE);
        shareView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != shareBitmap && !shareBitmap.isRecycled()) {
            shareBitmap.recycle();
            shareBitmap=null;
            System.gc();
        }
    }
}
